from django.shortcuts import render_to_response
from django.http import HttpResponse
from django.template import RequestContext
from digitaldiary.main.models import Note,Tag
from django.conf import settings
#from digitaldiary.main.forms import NoteForm
#from digitaldiary.main.common import get_tag_name
#from django.contrib.auth.views import context_instance
from django.forms.models import modelformset_factory
vars={}

#
# Tag-related views
#

def index(request):
    return render_to_response('index.html',vars,context_instance=RequestContext(request))

def taglist(request):
    vars['tags']=Tag.objects.all()
    return render_to_response('tag-list.html',vars,context_instance=RequestContext(request))

def taglookup(request):
    tags=Tag.objects.all()
    str=""
    for tag in tags: str+="%s _ %s\n"%(tag.name,tag.type)
    return HttpResponse(str)


# add tag to note (note has to exist) 
def tagadd(request):
	if request.method <> 'POST':
		return HttpResponse('no POST data')

	#get tag instance
	try:
		tag_name=get_tag_name(request.POST['tag_name'])
	except:
		return HttpResponse('no \'tag_name\' in POST')
	tag=get_tag_from_name(tag_name)

	#get note instance
	try:
		note_id=request.POST['note_id']
	except:
		return HttpResponse('no \'note_id\' in POST')
	
	note=get_note_from_id(note_id)
	
	#add tag to note
	note.tag_set.add(tag.id)
	note.save()
	return HttpResponse('OK')


#
# Note-related views
#

def notelist(request):
    vars['notes']=Note.objects.all()
    return render_to_response('note-list.html',vars,context_instance=RequestContext(request))

def noteadd(request,_id=None):
	if _id <> None:
		try:
			note=Note.objects.filter(id=_id)[0]
			vars['note']=note
		except:
			pass
	if request.method <> 'POST':
		form=modelformset_factory(Note)
		vars['note']=form()
		return render_to_response('note-add.html',vars,context_instance=RequestContext(request))
	return False
	return HttpResponse('ASD')
